package com.cskaoyan.util;

import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InstanceUtil {
    //返回实例对象不为空的成员
    @SneakyThrows
    public static List<String> getNoNullFields(Object obj){
        //存放不为空的成员的值
        List<String> list = new ArrayList<>();
        Class<?> clazz = obj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Object value = field.get(obj);
            if(value!=null){
                String name = field.getName();
                list.add(name);
            }
        }
        return list;
    }
    public static Object copyNonNullFields(List<String> fieldNames, Object source, Object target) {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        for (String fieldName : fieldNames) {
            try {
                Field sourceField = sourceClass.getDeclaredField(fieldName);
                Field targetField = targetClass.getDeclaredField(fieldName);

                sourceField.setAccessible(true);
                targetField.setAccessible(true);

                Object value = sourceField.get(source);

                if (value != null) {
                    targetField.set(target, value);
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // handle exception
            }
        }
        return target;
    }
}
